package com.rankeiot.core.excel;

import com.rankeiot.core.anno.ExcelTemplate;
import com.rankeiot.core.translator.Translator;

import java.io.InputStream;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

/**
 * 按批导入数据
 */
public class ExcelBatchImporter<T> implements Consumer<T> {
    private int batchSize=500;
    private InputStream in;
    private Map<String, Translator> translators=new HashMap<>();
    private Class<T> type;

    private List temp = new ArrayList<>();

    private long currentIndex=0;

    protected BatchImportHandler batchImportHandler;
    //限定导入sheet
    protected Set<Integer> sheets=new HashSet<>();

    public ExcelBatchImporter(InputStream in,Class<T> dataType){
        this.in=in;
        this.type=dataType;
       // setSheets();
    }
    public ExcelBatchImporter(InputStream in,Map<String, Translator> translators,Class<T> dataType){
        this.in=in;
        this.type=dataType;
        this.translators=translators;
       // setSheets();
    }
    public void translate(String field,Translator translator){
        translators.put(field,translator);
    }
    public void setBatchSize(int batchSize) {
        this.batchSize = batchSize;
    }

    protected void load(InputStream in,TypedRowHandler th){
        DataRowHandler dh = new DataRowHandler(th);
        ExcelLoader.load(in,dh);
    }
    public void start(BatchImportHandler<T> bh){
        batchImportHandler=bh;
        TypedRowHandler th = new TypedRowHandler(type, translators, this);
        load(in,th);
        if(temp.size()>0){
            onBatch(temp,currentIndex);
        }
    }

    private void onBatch(List<T> batch,long lastIndex){
        batchImportHandler.onBatch(batch,lastIndex);
    }

    @Override
    public void accept(T t) {
        if(temp.size()==batchSize){
            onBatch(temp,currentIndex);
            temp=new ArrayList();
        }
        temp.add(t);
        currentIndex++;
    }
}
